/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-02-26 16:57:25
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-22 14:07:50
 * @Description: file content
 */
import { Application } from "egg";
import { DataTypes, Model } from "sequelize";
import * as moment from "moment";

export interface sysLogInterface extends Model {
  /** 日志类别
   * 0 登录日志
   * 1 操作日志
   */
  type: 0 | 1;
  /** 日志分类名称 */
  type_name: string;
  /** 操作用户id */
  user_name: string;
  /** 请求路径url */
  request_url: string;
  /** 请求方法 */
  method: string;
  /** 请求参数 */
  params: string;
  /** 请求ip地址 */
  request_ip: string;
  /** 响应状态码 */
  response_status: number;
  /** 应用结果代码 */
  app_status: number | string;
  /** 操作结果 */
  result: string;
  /** 浏览器user agent */
  user_agent: string;
}

export default (app: Application) => {
  const model = app.model.define<sysLogInterface>(
    app.config.dbModel_prefix + "sys_log",
    {
      type: {
        field: "type",
        comment: "日志类别",
        type: DataTypes.INTEGER,
      },
      type_name: {
        field: "type_name",
        comment: "类别名称",
        type: DataTypes.STRING(26),
      },
      user_id: {
        field: "user_id",
        type: DataTypes.INTEGER,
        comment: "用户id", //若是登录等还不知道用户的id时默认为0
        defaultValue: 0,
      },
      user_name: {
        field: "user_name",
        type: DataTypes.STRING(30),
        comment: "操作用户",
      },
      request_url: {
        field: "req_url",
        type: DataTypes.STRING(300),
        comment: "请求路径url",
      },
      method: {
        field: "method",
        type: DataTypes.STRING(20),
        comment: "请求方法",
      },
      params: {
        field: "params",
        type: DataTypes.STRING(3000),
        comment: "请求参数",
      },

      request_ip: {
        field: "req_ip",
        type: DataTypes.STRING(22),
        comment: "请求ip地址",
      },
      response_status: {
        field: "res_status",
        type: DataTypes.STRING(10),
        comment: "响应状态码",
      },
      app_status: {
        field: "app_status",
        type: DataTypes.STRING(10),
        comment: "应用结果码",
      },
      result: {
        field: "result",
        type: DataTypes.STRING(80),
        comment: "结果说明",
      },
      user_agent: {
        field: "user_agent",
        type: DataTypes.STRING(200),
        comment: "前端浏览器user_agent",
      },
      time: {
        field: "time",
        type: DataTypes.INTEGER,
        comment: "执行耗时",
      },
      createdAt: {
        type: DataTypes.DATE,
        get() {
          // console.log(1);
          return moment((this as any).getDataValue("createdAt")).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        },
      },
      updatedAt: {
        type: DataTypes.DATE,
        get() {
          return moment((this as any).getDataValue("updatedAt")).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        },
      },
    }
  );

  return model;
};
